/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gestionnaire;

import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import modeles.tag;

/**
 *
 * @author elo
 */
@Stateless
public class gestionnaireTag {
    
    @PersistenceContext
    private EntityManager em;

    public void creerTags() {
        if(countTags() == 0){
            creeTag("FPS");
            creeTag("Jeu de tir");
            creeTag("Action");
            creeTag("Jeu de role");
            creeTag("RPG");
            creeTag("Aventure");
            creeTag("Strategie");
            creeTag("MMORPG");
            creeTag("Kids");
            creeTag("Simulation de vol");
            creeTag("Sport");
            creeTag("Danse");
            creeTag("Musique");
            creeTag("Combat");
            creeTag("MMO");
            creeTag("Activites recreatives");
            creeTag("Compilation");
            creeTag("Reflexion");
            creeTag("Multijoueur");
            creeTag("Internet");
            creeTag("Kinect");
            creeTag("Plate-forme");
            creeTag("Gestion");
            creeTag("Course");
        }
    }

    public tag getTagByName(String name){
        Query q = em.createQuery("select t from tag t where t.libelle like :nom");
        q.setParameter("nom", name);
        Collection<Object> result = q.getResultList();
        if(result.size() == 0)
            return null;
        else
            return (tag)result.toArray()[0];
    }

    public String getNomTagById(int id){
        Query q = em.createQuery("select c.libelle from tag c where c.id = :id");
        q.setParameter("id", id);
        Collection<Object> result = q.getResultList();
        if(result.size() == 0)
            return null;
        else
            return result.toArray()[0].toString();
    }

    public tag creeTag(String nom) {
        tag t = new tag(nom);
        em.persist(t);
        return t;
    }

    public Collection<tag> getAllTags() {
        // Exécution d'une requête équivalente à un select *
        Query q = em.createQuery("select t from tag t order by t.libelle asc");
        return q.getResultList();
    }

    public int countTags() {
        Query q = em.createQuery("select count(t) from tag t");
        int nb = Integer.parseInt(q.getSingleResult().toString());
        return nb;

    }
}
